package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;

import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryMapper {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        Page<Category> categoryPage = new Page<Category>();
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getCreateTime);
        categoryService.page(categoryPage,lqw);
        return R.success(categoryPage);
    }

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 根据id查询分类,回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id){
        Category category = categoryService.getById(id);
        return R.success(category);
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        categoryService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 返回不同分类的所有菜品
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(int type){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Category::getType,type);
        lqw.orderByDesc(Category::getCreateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
